<template>
  <el-container class="white-index">
    <el-header style="height:40px">
      <Navmenu @sendTo="showItem"></Navmenu>
    </el-header>
    <el-main v-if="show">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="left" @click="todetail()">
              <img src="../assets/img/home/card.jpg" alt="#" />
              <span style="font-size:14px;font-weight:bold">{{username}}的Thingjs大世界</span>
            </div>
            <el-divider direction="vertical"></el-divider>
            <el-dropdown size="mini">
              <span class="el-icon-setting"></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>修改房间名称</el-dropdown-item>
                <el-dropdown-item divided>设置房间密码</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
    <el-main v-else>
      <div class="data-oper">
        <div class="hierarchy">
          <a href="javascript:void(0)" @click="root">根目录</a>
          <span v-for="(item,index) in folderList">
            __
            <a href="javascript:void(0)" @click="in_folder(index)">{{item}}</a>
          </span>
        </div>
        <span class="item create" @click="openAdd()">
          <img src="../assets/img/home/xinz.png" alt="创建" />创建文件夹
        </span>
        <span class="item upload" @click="upload()">
          <img src="../assets/img/home/shc.png" alt="上传" />上传
        </span>
      </div>
      <el-table :data="tableFile" size="mini">
        <el-table-column label="名称">
          <template slot-scope="scope">
            <span class="file-icon file-folder" @click="secondFile"></span>
            <a href="javascript:void(0)" @click="select_folder(scope.row)">{{scope.row.name}}</a>
          </template>
        </el-table-column>
        <el-table-column label="大小" prop="size" align="center"></el-table-column>
        <!-- <el-table-column label="创建者" align="center">{{username}}</el-table-column> -->
        <el-table-column label="时间" prop="mtime" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <span class="item li3" title="重命名" @click="rename(scope.row.name)"></span>
            <span class="item li5" title="删除" @click="remove(scope.row.name)"></span>
          </template>
        </el-table-column>
      </el-table>
      <div class="file_box"></div>
    </el-main>
    <!-- 重命名文件夹模态框-->
    <el-dialog title="修改文件夹名称" :visible.sync="addVisible" @close="bookclose" center width="30%">
      <el-input
        v-model="inputName"
        :placeholder="oldFileName"
        onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureEdit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除文件夹模态框 -->
    <el-dialog title="删除文件夹" :visible.sync="removeVisible" center width="30%">
      <span>
        确定要删除
        <span style="color:red">{{removeName}}</span>吗？
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="removeVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureRemove()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传文件模态框 -->
    <el-dialog title="上传文件" :visible.sync="uploadVisible" width="30%">
      <el-upload
        class="upload-demo"
        drag
        ref="upload"
        :action="loadUrl"
        :headers="myHeaders"
        :data="extraData"
        :name="photos"
        :on-success="onSuccess"
        :on-change="onChange"
        :on-remove="removeList"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="uploadVisible = false">取 消</el-button>
        <el-button type="primary" v-show="isUpload" @click="uploadFunc2()">上 传</el-button>
        <el-button type="primary" v-show="!isUpload" :loading="true">上传中</el-button>
      </span>-->
    </el-dialog>
  </el-container>
</template>
<script>
import { FileOption, FileLogin, getUserInfo } from "../service/api";
import Navmenu from "../page/component/Navmenu";
export default {
  data() {
    return {
      show: true, //房间列表显示
      tableFile: [],
      username: window.localStorage.getItem("username"),
      addVisible: false, //修改文件夹模态框
      removeVisible: false, //删除文件夹模态框
      oldFileName: "",
      inputName: "", //文件夹名称
      removeName: "",
      webSocket: null,
      uploadVisible: false, //上传文件
      loadUrl: "https://192.168.96.105:6064/documentation/document/create",
      myHeaders: null,
      extraData: null,
      photos: "photos",
      isUpload: true,
      folderList: [],
    };
  },
  components: {
    Navmenu
  },
  mounted() {
    this.getFileList();

    console.log(this.getUserInfo1())
  },
  methods: {
    select_folder(item) { // 点击了文件夹
      console.log(item)
      if (item.type == 'folder') { // 文件夹
        this.folderList.push(item.name);
        this.getFileList();
      } else { // 图片，pdf等可预览文件

      }
    },
    root() { // 点击根目录
      this.folderList = [];
      this.getFileList();
    },
    in_folder(index) { // 点击顶部的文件导航
      this.folderList.splice(index + 1)
      this.getFileList();
    },
    showItem(data) {
      if (data == 0) {
        this.show = true;
      } else {
        this.show = false;
      }
    },
    //白板详情页
    todetail() {
      this.$router.push({ path: "/wsBoard", query: { id: '199' } });
    },
    initWebSocket(file) {
      console.log(file);
      //初始化weosocket
      const wsurl = "wss://192.168.96.105:9091";
      if (this.webSocket == null) {
        this.webSocket = new WebSocket(wsurl);
      }
      console.log(this.webSocket);

      this.webSocket.onopen = (e) => {
        console.log('account:', window.localStorage.getItem("account"));
        let path = "/" + this.folderList.join('/');
        this.webSocket.send(
          JSON.stringify({
            appid: "minyanan_chanpin",
            account: window.localStorage.getItem("account"),
            code: 100,
            name: file.name,
            size: file.size,
            path: path //上传目录
          })
        );
      };
      this.webSocket.onmessage = (e) => {
        console.log('eeeeeeok:', e)
        if (e.data == "ok") {
          //开始上传
          var buffer_size = 2097152,
            start = 0,
            end = buffer_size;
          //创建缓冲区
          var reader = new FileReader();
          reader.onload = (e) => {
            console.log('进入onload函数', reader);
            this.webSocket.send(reader.result);
            //循环加载
            if (end < file.size) {
              start += buffer_size;
              end += buffer_size;
              if (end > file.size) end = file.size;
              //分片读入
              reader.readAsArrayBuffer(file.slice(start, end));
            } else {
              // item.hide(3000);
              // setTimeout(function() {
              //   f.dir();
              //   item.parent().remove();
              //   ws.close();
              // }, 3000);
              this.$message({ message: '上传成功！', type: 'success' })
              this.$refs['upload'].clearFiles();
              this.uploadVisible = false
              this.getFileList();
            }
          };
          // reader.onprogress = function(e) {
          //   var width = parseInt((end / file.size) * 100);
          //   if (width > 100) width = 100;
          //   if (width > 60 && width < 90) {
          //     progress
          //       .removeClass("progress-bar-info")
          //       .addClass("progress-bar-warning");
          //   } else if (width >= 90) {
          //     progress
          //       .removeClass("progress-bar-warning")
          //       .addClass("progress-bar-success");
          //   }
          //   progress.attr("style", "width:" + width + "%").text(width + "%");
          // };
          console.log(file);
          // reader.readAsArrayBuffer(file);
          reader.readAsArrayBuffer(file.slice(start, end));
        }
      };
    },
    //获取文件夹列表
    async getFileList() {
      let path = "/" + this.folderList.join('/');
      console.log(path)
      let data = {
        account: window.localStorage.getItem("account"),
        appid: "minyanan_chanpin",
        action: "dir",
        path: path, //相对于哪个目录操作
        // type: "folder", //文件夹标识
        sort: "0",
        keyword: ""
      };
      console.log("===", data);
      FileOption(data).then(res => {
        console.log("文件夹列表返回数据", res);
        if (res.code == 100) {
          this.tableFile = res.result;
        }
      });
    },
    async getUserInfo1() {
      let data = {
        query: {
          account: "=" + window.localStorage.getItem("account")
        }
      };
      let roomid = getUserInfo(data).then(res => {
        console.log("getUserInfo:", res.info.rows[0].videoRoomId);
        return res.info.rows[0].videoRoomId
      });
      return roomid;
    },
    // 创建文件夹列表
    async openAdd() {
      // this.addVisible=true;
      let path = "/" + this.folderList.join('/');
      console.log(path)
      let data = {
        account: window.localStorage.getItem("account"),
        appid: "minyanan_chanpin",
        action: "newFolder",
        path: path //相对于哪个目录操作
      };
      console.log(data)
      FileOption(data).then(res => {
        console.log("创建文件夹返回结果", res);
        if (res.code == 100) {
          this.getFileList();
        }
      });
    },
    // 修改文件夹打开模态窗
    rename(name) {
      this.oldFileName = name;
      this.addVisible = true;
    },
    // 修改文件夹名称
    async sureEdit() {
      let data = {
        account: window.localStorage.getItem("account"),
        appid: "minyanan_chanpin",
        action: "rename",
        file_name: this.oldFileName, //操作文件
        new_name: this.inputName //操作文件
      };
      console.log("修改参数", data);
      FileOption(data).then(res => {
        console.log("修改文件夹返回结果", res);
        if (res.code == 100) {
          this.getFileList();
          this.addVisible = false;
        } else {
          this.$message.error("文件夹名称不能重复");
        }
      });
    },
    // 修改文件夹模态框关闭
    bookclose() {
      this.inputName = "";
    },
    // 删除文件夹模态框
    remove(name) {
      this.removeName = name;
      this.removeVisible = true;
    },
    // 删除文件夹
    async sureRemove() {
      let path = "/" + this.folderList.join('/');
      let data = {
        account: window.localStorage.getItem("account"),
        appid: "minyanan_chanpin",
        action: "remove",
        path: path + "/" + this.removeName //操作文件
      };
      console.log(path + "/" + this.removeName)
      FileOption(data).then(res => {
        if (res.code == 100) {
          this.getFileList();
          this.removeVisible = false;
        }
      });
    },
    // 进入二级文件
    secondFile() { },
    // 上传按钮点击
    upload() {
      this.fileLogin();
    },
    // 上传之前先登录
    fileLogin() {
      let obj = {
        account: "m18629246330",
        pass: "11111111",
        serial: "0FCC95B067470EAC" //序列号
      };
      FileLogin(obj).then(res => {
        console.log(">>>>>>>", res);
        if (res.ret == 1) {
          window.localStorage.setItem("uploadToken", res.info.token);
          this.extraData = {
            flag_ipfs: 1,
            flag_convert: 1
          };
          this.myHeaders = {
            token: res.info.token
          };
          this.uploadVisible = true;
        }
      });
    },
    onChange(file, fileList) {
      console.log(fileList[0])
    },
    onSuccess(response, file, fileList) {
      console.log('上传成功！', fileList[0])
      // console.log(response, file, fileList)
      this.initWebSocket(fileList[0].raw);
    },
    removeList(file, fileList) { },
    // 上传按钮点击
    uploadFunc2() { }
  }
};
</script>
<style lang="scss">
.white-index {
  .el-header {
    background-color: #fff;
  }
  .el-main {
    .el-row {
      .el-col {
        margin-bottom: 10px;
        .el-card {
          text-align: left;
          position: relative;
          .el-card__body {
            padding: 0px;
            .left {
              padding: 10px;
              display: inline-block;
              img {
                height: 80px;
                vertical-align: middle;
              }
              span {
                margin-left: 15px;
              }
            }
            .left:hover {
              background-color: rgba(0, 3, 3, 0.1);
            }
            .el-divider {
              height: 5em;
              margin: 0;
              margin-right: 8px;
            }
          }
        }
      }
    }
    .data-oper {
      background-color: #fff;
      height: 20px;
      text-align: right;
      padding: 15px 0;
      position: relative;
      .hierarchy {
        position: absolute;
        top: 15px;
        left: 10px;
        span {
          margin: 0;
        }
        a {
          color: #634840;
        }
      }
      span {
        font-size: 14px;
        margin: 0 10px;
        color: #ee6133;
        cursor: pointer;
        img {
          width: 14px;
          margin: 0 5px 0 0;
          vertical-align: middle;
        }
      }
    }
    .el-table {
      .file-icon {
        display: inline-block;
        overflow: hidden;
        vertical-align: middle;
        width: 20px;
        height: 20px;
        margin-right: 6px;
        color: transparent;
      }
      .item {
        display: inline-block;
        width: 16px;
        height: 16px;
        cursor: pointer;
        margin: 0 5px 0 0;

        &.li1 {
          background: url("../assets/img/project/bb.png") no-repeat center
            center;
          background-size: 18px 12px;

          &:hover {
            background: url("../assets/img/project/bb1.png") no-repeat center
              center;
            background-size: 18px 12px;
          }
        }

        &.li2 {
          background: url("../assets/img/project/xiazai.png") no-repeat center
            center;
          background-size: 16px 16px;

          &:hover {
            background: url("../assets/img/project/xiazai1.png") no-repeat
              center center;
            background-size: 16px 16px;
          }
        }

        &.li3 {
          background: url("../assets/img/project/bj.png") no-repeat center
            center;
          background-size: 16px 16px;

          &:hover {
            background: url("../assets/img/project/bj1.png") no-repeat center
              center;
            background-size: 16px 16px;
          }
        }

        &.li4 {
          background: url("../assets/img/project/more.png") no-repeat center
            center;
          background-size: 16px 16px;

          &:hover {
            background: url("../assets/img/project/more1.png") no-repeat center
              center;
            background-size: 16px 16px;
          }
        }

        &.li5 {
          background: url("../assets/img/project/sc.png") no-repeat left center;
          background-size: 16px 16px;

          &:hover {
            background: url("../assets/img/project/sc1.png") no-repeat left
              center;
            background-size: 16px 16px;
            color: #ee6133;
          }
        }

        &.li6 {
          background: url("../assets/img/project/yidong.png") no-repeat left
            center;
          background-size: 16px 16px;

          &:hover {
            background: url("../assets/img/project/yidong1.png") no-repeat left
              center;
            background-size: 16px 16px;
            color: #ee6133;
          }
        }
      }
    }
  }
}
</style>

